package com.imooc;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * @describte:使用Redis配置限流
 * @program:foodie-cloud
 * @author:zhengdp
 * @create:2021-10-07 00:39:54
 **/
@Configuration
public class RedisLimiterConfiguration {

    // 什么级别的限流，就要使用不同的Key
    // HostAddress 的 key
    @Bean
    @Primary
    public KeyResolver remoteAddrKeyResolver(){
        return exchange -> Mono.just(
          exchange.getRequest()
                .getRemoteAddress()
                .getAddress()
                .getHostAddress()
        );
    }

    // 限流组件
    @Bean("redisLimiterUser")
    @Primary // Gateway 会自动装配，所以需要指定一下
    public RedisRateLimiter redisRateLimiterUser(){
        return new RedisRateLimiter(10,20);
    }

    @Bean("redisLimiterItem")
    public RedisRateLimiter redisRateLimiterItem(){
        return new RedisRateLimiter(20,50);
    }

    // todo 实现 in-memory 级别的限流工具类 限流器
}
